package com.tanhua.server.service;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.CommentLikeApi;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.CommentLike;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class CommentLikeService {

    @DubboReference
    private CommentLikeApi commentLikeApi;
    @DubboReference
    private CommentApi commentApi;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 评论点赞
     *
     * @param commentId
     * @return
     */
    public Integer likeComment(String commentId) {
        //判断是否已经点赞
        boolean flag = commentLikeApi.haslike(commentId, UserHolder.getUserId());
        if (flag) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //保存点赞数据
        CommentLike commentLike = new CommentLike();
        commentLike.setCommentId(new ObjectId(commentId));
        commentLike.setUserId(UserHolder.getUserId());
        commentLike.setCreated(System.currentTimeMillis());
        commentLikeApi.save(commentLike);

        Integer count = commentApi.update(commentId);
        //点赞数据存入redis
        String key = Constants.LIKE_COMMENT_KEY + commentId;
        String hashKey = Constants.LIKE_COMMENT_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    /**
     * 取消评论点赞
     * @param commentId
     * @return
     */
    public Integer disLikeComment(String commentId) {
        //判断是否已经点赞
        boolean flag = commentLikeApi.haslike(commentId, UserHolder.getUserId());
        if (!flag) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //删除点赞数据
        commentLikeApi.delete(commentId,UserHolder.getUserId());
        Integer count = commentApi.disLike(commentId);
        //删除redis的点赞数据
        String key = Constants.LIKE_COMMENT_KEY + commentId;
        String hashKey = Constants.LIKE_COMMENT_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }
}
